<?php

class SuggestController extends Controller {

    private $_form;
    public $layout = "columns2";

    public function actions() {
        return array('captcha' => array('class' => 'CCaptchaAction', 'transparent' => true));
    }

    public function accessRules() {
        return array(array('allow', 'actions' => array('create'), 'users' => array("@"),), array('allow', 'actions' => array("list", 'AjaxList', 'view', 'rss', 'helped'), 'users' => array("*"),), array('allow', 'actions' => array('delete'), 'expression' => 'Y::user()->isModerator()',), array('deny', 'users' => array('*')));
    }

    public function actionAjaxList() {
        $criteria = new CDbCriteria();
        $criteria->limit = 3;
        $criteria->condition = 'status = 0';
        $criteria->order = 't_update DESC';
        $suggests = Suggest::search($criteria, true, true);
        $this->renderPartial('listAjax', compact("suggests"));
    }

    public function actionClose() {
        $user = User::model()->findByPk(Y::userId());
        $suggest = Suggest::model()->findByPk($_GET['id']);
        if($suggest && $user && $suggest->owner_id != $user->id) {
            Y::flashRedir('errorMessage', 'Это предложение вам не пренадлежит', "suggest/view", array("id" => $suggest->id));
        } else {
            $suggest->status = 1;
            $suggest->save();

            Y::flashRedir('success-block', 'Ваше предложение было закрыта', "suggest/view", array("id" => $suggest->id));
        }
    }

    public function actionUp() {
        $user = User::model()->findByPk(Y::userId());
        $suggest = Suggest::model()->findByPk($_GET['id']);
        if($suggest && $user && $suggest->owner_id != $user->id) {
            Y::flashRedir('errorMessage', 'Это предложение вам не пренадлежит', "suggest/view", array("id" => $suggest->id));
        }
        if($suggest && $user && $user->rating >= Y::param('costUp')) {
            $suggest->up();
            $user->downRating(Y::param('costUp'));
            Y::flashRedir('success-block', 'Ваше предложение было поднята', "suggest/view", array("id" => $suggest->id));
        } elseif($suggest && $user && $user->rating < Y::param('costUp')) {
            Y::flashRedir('errorMessage', 'У вас не хватает ретинга.', "suggest/view", array("id" => $suggest->id));
        } else {
            Y::redir("user/login");
        }
    }

    public function actionHelped() {
        if(Y::isAuthed()) {
           //
            $item = Suggest::model()->findByPk($_GET['item_id']);
            $owner = User::model()->findByPk($item->owner_id);
            if($owner && $item && $item->status == 0) {
                $owner->helped = $owner->helped + 1;
                $owner->save();

                $user = User::model()->findByPk(Y::userId());
                if($user) {
                    $help = new HelpsSuggest();
                    $help->item_id = $item->id;
                    $help->user_id = $user->id;
                    $help->save();
                }
            }
        }
        $this->redirect("/suggest/" . $_GET['item_id']);
    }

    public function actionDelete() {
        $suggest = $this->loadSuggest($_GET['id']);
        $suggest->delete();
        Y::flash("success-block", "Предложение успешно удалено.");
        $this->redirect("/suggest/list");
    }

    public function actionCreate() {
        $this->keyWord = "create, service";
        $this->description = "Создание предложения";
        $this->pageTitle = 'Создание предложения';

        $this->breadcrumbs = array("name" => '<a href="' . Y::url("suggest/list") . '">Список предложений</a>',);
        $FormNewSuggest = new FormNewSuggest();
        $form = new CForm($FormNewSuggest->config, $FormNewSuggest);
        if($form->submitted('send') && $form->validate()) {
            $FormNewSuggest->createNew();
            Yii::app()->user->setFlash("success-block", 'Ваше предложение успешно создано');
            $this->redirect("/suggest/list");
        }
        $this->render('create', array('form' => $form));
    }

    public function actionList() {
        $this->keyWord = "create, suggest";
        $this->description = "Список предложений";
        $this->pageTitle = 'Список предложений';

        $criteria = new CDbCriteria();
        $criteria->with = array("owner", "tags", 'cont_comments');
        $this->breadcrumbs = array("name" => "Список предложений",);
        if(isset($_GET['search'])) {
            $criteria->addSearchCondition('title', $_GET['search'], true, "OR");
            $criteria->addSearchCondition('text', $_GET['search'], true, "OR");
        }
        if(isset($_GET['filter'])) {
            $tag = Tags::model()->find("name = ?", array($_GET['filter']));
            $suggest_ids = array();
            if($tag){
                $ts = TagsSuggest::model()->findAll("tag_id = ?", array($tag->id));
                foreach($ts as $t) {
                    $suggest_ids[] = $t->item_id;
                }
                $criteria->addInCondition('t.id', $suggest_ids);
            }
        }
        if(isset($_GET['userFilter'])) {
            $filter = UserFilter::model()->findByPk($_GET['userFilter']);
            if($filter && $filter->owner_id == Y::userId()) {
                $c = new CDbCriteria();
                $c->addInCondition('tag_id', explode(",", $filter->tag_ids));
                $suggest_ids = array();
                $ts = TagsSuggest::model()->findAll($c);
                foreach($ts as $t) {
                    $suggest_ids[] = $t->item_id;
                }
                $criteria->addInCondition('t.id', $suggest_ids);
            }
        }
        $sort = new CSort();
        $sort->sortVar = 'sort';
        $sort->defaultOrder = 't.t_create DESC';
        $sort->multiSort = true;
        $sort->attributes = array('t_create' => array('asc' => 't.t_create ASC', 'desc' => 't.t_create DESC', 'label' => 'дате',), 'status' => array('asc' => 't.status ASC', 'desc' => 't.status DESC', 'label' => 'статусу',),);
        $suggests = new CActiveDataProvider('Suggest', array('criteria' => $criteria, 'sort' => $sort, 'pagination' => array('pageSize' => Y::param("countInPage"),),));
        $this->render('list', compact("suggests"));
    }

    public function actionView() {

        $suggest = $this->loadModel();
        if(Y::user()->getState('viewSuggestId') != $suggest->id){
            $suggest->count_view =  $suggest->count_view + 1;
            $suggest->save();
             Y::user()->setState('viewSuggestId',$suggest->id);
        }

        $this->keyWord = YText::getKeyword($suggest->text);
        $this->description = YText::getDescription($suggest->text, 255, '');
        $this->pageTitle = $suggest->title;

        $comment = $this->newComment($suggest);
        $this->breadcrumbs = array("name" => CHtml::link("Список предложений", "/service/list"), "name2" => $suggest->title,);
        $item_suggests = array();
        if($suggest->owner_id == Y::userId()) {
            $item_suggests = $suggest->findSimilarSuggest(Y::param('limitSimilar'));
        }
        $item_services = $suggest->findSimilarService(Y::param('limitSimilar'));
        $helps = HelpsSuggest::model()->findAll('item_id = ?', array($suggest->id));
        $is_helped = array();
        foreach($helps as $help) {
            $is_helped[] = $help->user_id;
        }
        $this->render('view', array('suggest' => $suggest, 'comment' => $comment, 'is_helped' => $is_helped, 'item_services' => $item_services, 'item_suggests' => $item_suggests,));
    }

    public function loadModel() {
        if($this->_form === null) {
            if(isset($_GET['id'])) {
                $this->_form = Suggest::model()->with(array('comments.owner', 'rt' => array('condition' => 'rt.user_id = ' . Y::userId() . ' AND rt.type=' . Rating::TYPE_SUGGEST), 'comments.rt'))->findByPk($_GET['id']);
            }
            if($this->_form === null) throw new CHttpException(404, 'Нет такой страницы');
        }
        return $this->_form;
    }

    protected function newComment($post) {
        $comment = new Comment;
        $comment->post_id = $post->id;
        $comment->type = Comment::TYPE_SUGGEST;
        if(isset($_POST['ajax']) && $_POST['ajax'] === 'comment-form') {
            echo CActiveForm::validate($comment);
            Yii::app()->end();
        }
        if(isset($_POST['Comment'])) {
            $comment->attributes = $_POST['Comment'];
            $comment->save();

            $post->t_lastcomment = time();
            $post->save();

            if($post->send_email == 1 && (time() - $post->last_send_email) > 24 * 60 * 60) {
                $this->sendMailNewComment($post);
                $post->last_send_email = time();
                $post->save();
            }
            $this->refresh();
        }
        return $comment;
    }

    protected function sendMailNewComment($post) {
        $user = User::model()->findByPk($post->owner_id);
        if(!$user->isOnline()) {
            $this->sendMail($user->email, '../email/new_comment_suggest', array('model' => $user, "post" => $post), 'Ответ в теме "' . $post->title . '"');
        }
    }

    public function actionRss() {
        Yii::import('ext.feed.*');
        $feed = new EFeed();
        $feed->title = 'Предложения';
        $feed->link = Y::baseUrl(true);
        $feed->description = 'Список предложений';
        //@todo: Нужно потом сюда лого сделать!!
        $feed->setImage('hyho.by', 'http://hyho.by', 'http://trendclub.ru/upload/media/images/mik89/rss.jpg');
        $feed->addChannelTag('language', 'ru');
        $feed->addChannelTag('pubDate', date(DATE_RSS, time()));
        $criteria = new CDbCriteria();
        $criteria->limit = 20;
        $criteria->order = "t.t_create desc";
        $criteria->with = "owner";
        $suggests = Suggest::model()->findAll($criteria);
        foreach($suggests as $suggest) {
            $item = $feed->createNewItem();
            $item->title = $suggest->title;
            $item->link = Y::baseUrl(true) . "/services/" . $suggest->id;
            $item->date = $suggest->t_create;
            $item->description = strip_tags(YText::characterLimiter($suggest->text, 500));
            $item->addTag('author', $suggest->owner->username);
            $item->addTag('guid', Y::baseUrl(true) . "/suggest/" . $suggest->id, array('isPermaLink' => 'true'));
            $feed->addItem($item);
        }
        $feed->generateFeed();
    }
}
